﻿using Domain.Entitys.Base_Manage;
using Domain.IRepositorys.Base_Manage;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys.Base_Manage
{
    public class DeptRepository : IDeptRepository
    {
        private readonly MyDbContext myDbContext;

        public DeptRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 添加部门信息
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeptAddAsync(Sys_Dept dept)
        {
            await myDbContext.Sys_Dept.AddAsync(dept);
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 逻辑删除部门信息
        /// </summary>
        /// <param name="dept_id"></param>
        /// <param name="del"></param>
        /// <returns></returns>
        public async Task<int> DeptDeleteAsync(Sys_Dept dept)
        {
            //FindAsync异步方法，用于 查找某个对象或数据
            Sys_Dept dept1 = await myDbContext.Sys_Dept.FindAsync(dept.Dept_id);
            dept1.Del_flag = dept.Del_flag;
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 查询全部部门
        /// </summary>
        /// <returns></returns>
        public async Task<List<Sys_Dept>> DeptOptAsync()
        {
            return await myDbContext.Sys_Dept.Where(d => d.Del_flag == '0').ToListAsync();
        }

        /// <summary>
        /// 修改部门信息
        /// </summary>
        /// <param name="dept"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DeptUpdateAsync(Sys_Dept dept)
        {

            Sys_Dept dept1 = myDbContext.Sys_Dept.Find(dept.Dept_id);
            dept1.Parent_id = dept.Parent_id;
            dept1.Dept_name = dept.Dept_name;
            dept1.Leader = dept.Leader;
            dept1.Status = dept.Status;
            dept1.Phone = dept.Phone;
            dept1.Update_by = dept.Update_by;
            dept1.Update_time = dept.Update_time;
            myDbContext.Sys_Dept.Update(dept1);
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据部门名称和负责人分页查询
        /// </summary>
        /// <param name="dept_name"></param>
        /// <param name="leader"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<Sys_Dept> GetDepts(string dept_name, string leader, int currentPage, int pageSize)
        {
            // 创建基础查询
            IQueryable<Sys_Dept> query = myDbContext.Sys_Dept.Where(d => d.Del_flag == '0');

            // 添加条件筛选
            if (!string.IsNullOrEmpty(dept_name))
            {
                query = query.Where(d => d.Dept_name == dept_name);
            }
            if (!string.IsNullOrEmpty(leader))
            {
                query = query.Where(d => d.Leader == leader);
            }

            // 添加分页
            var depts = query.Skip((currentPage - 1) * pageSize)
                            .Take(pageSize)
                            .ToList();

            return depts;
        }

        /// <summary>
        /// 根据部门名称和负责人查询总数
        /// </summary>
        /// <param name="dept_name"></param>
        /// <param name="leader"></param>
        /// <returns></returns>
        public int GetDeptsCount(string dept_name, string leader)
        {
            // 创建基础查询
            IQueryable<Sys_Dept> query = myDbContext.Sys_Dept.Where(d => d.Del_flag == '0');

            // 添加条件筛选（与GetDepts方法保持一致）
            if (!string.IsNullOrEmpty(dept_name))
            {
                query = query.Where(d => d.Dept_name == dept_name);
            }
            if (!string.IsNullOrEmpty(leader))
            {
                query = query.Where(d => d.Leader == leader);
            }

            // 返回计数
            return query.Count();
        }

        /// <summary>
        /// 查询部门信息及其子级部门
        /// </summary>
        /// <returns></returns>
        public List<Sys_Dept_Trees> Get_Dept_Trees(string name)
        {
            // 获取所有未删除的部门
            List<Sys_Dept> allDepts = myDbContext.Sys_Dept
                .Where(d => d.Del_flag == '0')
                .ToList();

            // 先构建完整树
            var fullTree = CreateMenu(allDepts, 0);

            if (string.IsNullOrEmpty(name))
                return fullTree;

            // 新的过滤逻辑：返回匹配节点及其完整子树
            return FilterTreeWithFullChildren(fullTree, name);
        }


        public List<Sys_Dept_Trees> CreateMenu(List<Sys_Dept> sys_Depts, int groupId)
        {
            //获取父级数据
            List<Sys_Dept> sys_Depts1 = sys_Depts.Where(j => j.Parent_id == groupId).ToList();
            List<Sys_Dept_Trees> sys_Dept_Trees = new List<Sys_Dept_Trees>();
            foreach (Sys_Dept sys_Dept in sys_Depts1)
            {
                Sys_Dept_Trees t = new Sys_Dept_Trees()
                {
                    Dept_id = sys_Dept.Dept_id,
                    Dept_name = sys_Dept.Dept_name,
                    Parent_id = sys_Dept.Parent_id,
                    children = CreateMenu(sys_Depts, sys_Dept.Dept_id)
                };
                sys_Dept_Trees.Add(t);
            }
            return sys_Dept_Trees;
        }

        private List<Sys_Dept_Trees> FilterTreeWithFullChildren(List<Sys_Dept_Trees> nodes, string name)
        {
            var result = new List<Sys_Dept_Trees>();

            foreach (var node in nodes)
            {
                // 如果当前节点匹配，保留整个子树
                if (node.Dept_name.Contains(name))
                {
                    result.Add(node); // 包含所有子节点
                    continue;
                }

                // 否则递归检查子节点
                var filteredChildren = FilterTreeWithFullChildren(node.children, name);
                if (filteredChildren.Count > 0)
                {
                    // 如果子节点有匹配，保留当前节点（但只保留匹配的子树路径）
                    var newNode = new Sys_Dept_Trees
                    {
                        Dept_id = node.Dept_id,
                        Dept_name = node.Dept_name,
                        Parent_id = node.Parent_id,
                        children = filteredChildren
                    };
                    result.Add(newNode);
                }
            }

            return result;
        }
    }
}
